package initter

import (
	"GoodSrv/common/global"
	consule "GoodSrv/vender/consul"
	"encoding/json"
	"fmt"
	"github.com/hashicorp/consul/api"
	"github.com/nacos-group/nacos-sdk-go/v2/clients"
	"github.com/nacos-group/nacos-sdk-go/v2/common/constant"
	"github.com/nacos-group/nacos-sdk-go/v2/vo"
	uuid "github.com/satori/go.uuid"
	"github.com/spf13/viper"
	"go.uber.org/zap"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"gorm.io/gorm/schema"
	"log"
	"net"
	"os"
	"time"
)

// main之前加载
func init() {
	IniLogger()   //日志
	InitConfig()  //配置文件
	InitDB()      //初始化数据库
	InitPort()    //动态端口
	InitConsule() //初始化consule
}

// 加载日志
func IniLogger() {
	config := zap.NewDevelopmentConfig()
	config.OutputPaths = []string{
		"/Users/fuyx/GolandProjects/ShopProject/MxShopApi/BaseProjetApi/log/api.log",
		"stderr",
	}
	//构建并初始化
	logger, _ := config.Build()
	//替换为全局变量
	zap.ReplaceGlobals(logger)
}

// 初始化数据库
func InitDB() {
	m := global.GlobalConfig.Mysql
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local",
		m.User, m.Password, m.Host, m.Port, m.Db)
	newLogger := logger.New(
		log.New(os.Stdout, "\r\n", log.LstdFlags), // io writer
		logger.Config{
			SlowThreshold: time.Second,   // 慢 SQL 阈值
			LogLevel:      logger.Silent, // Log level
			Colorful:      true,          // 禁用彩色打印
		},
	)

	// 全局模式
	var err error
	global.DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{
		NamingStrategy: schema.NamingStrategy{
			SingularTable: true,
		},
		Logger: newLogger,
	})
	if err != nil {
		panic(err)
	}
	zap.S().Infow("数据库初始化成功", zap.Int("code", 200))
}

// 加载全局配置项目(从yaml文件读取配置并设置全局变量)
func InitConfig() {
	//默认加载配置项  以全局变量的形式输出
	//初始化
	v := viper.New()
	//设置配置文件   -- nacos配置
	v.SetConfigFile("/Users/fuyx/GolandProjects/ShopProject/MxShopSrv/BaseProjetRpc/application.yaml")
	if err := v.ReadInConfig(); err != nil {
		panic(err)
	}
	// 全局变量定义
	NacosConfig := global.NacosConfig{}
	//读取的时候层级关系对应
	if err := v.Unmarshal(&NacosConfig); err != nil {
		panic(err)
	}
	global.NacosServer = &NacosConfig
	//从nacos中读取配置信息
	serverConfig := []constant.ServerConfig{
		{
			IpAddr: global.NacosServer.Host,
			Port:   uint64(global.NacosServer.Port),
		},
	}

	constantClient := constant.ClientConfig{
		NamespaceId:         global.NacosServer.NameSpaceId, // 如果需要支持多namespace，我们可以场景多个client,它们有不同的NamespaceId
		TimeoutMs:           5000,
		NotLoadCacheAtStart: true,
		LogDir:              "/tmp/nacos/log",
		CacheDir:            "/tmp/nacos/cache",
		LogLevel:            "debug",
	}

	configClient, err := clients.CreateConfigClient(map[string]interface{}{
		"serverConfigs": serverConfig,
		"clientConfig":  constantClient,
	})
	if err != nil {
		panic(err)
	}

	content, err := configClient.GetConfig(vo.ConfigParam{
		DataId: global.NacosServer.DataId,
		Group:  global.NacosServer.Group})

	if err != nil {
		panic(err)
	}
	//监听
	//err = configClient.ListenConfig(vo.ConfigParam{
	//	DataId: global.NacosServer.DataId,
	//	Group:  global.NacosServer.Group,
	//	OnChange: func(namespace, group, dataId, data string) {
	//		fmt.Println("group:" + group + ", dataId:" + dataId + ", data:" + data)
	//	},
	//})
	//time.Sleep(
	//	time.Second,
	//)
	//json格式
	//想要将一个json字符串转换成struct，需要去设置这个struct的tag
	ServerConfig := global.ServerConfig{}
	err = json.Unmarshal([]byte(content), &ServerConfig)
	global.GlobalConfig = &ServerConfig
}

// 动态生成端口
func InitPort() {
	//定义协议和地址
	addr, err := net.ResolveTCPAddr("tcp", "localhost:0")
	if err != nil {
		//zap.S().Infow("生成端口本地链接有误", zap.Error(err))
		panic(err)
	}
	//监听
	watch, err := net.ListenTCP("tcp", addr)
	//关闭监听
	defer watch.Close()
	//global.Port = watch.Addr().(*net.TCPAddr).Port
	global.Port = 9999
	zap.S().Infow("动态生成端口为:::", zap.Int("port", global.Port))
}

// 注册consule
func InitConsule() {
	config := api.DefaultConfig()
	config.Address = fmt.Sprintf("%s:%d", global.GlobalConfig.Consule.Host, global.GlobalConfig.Consule.Port)
	consuleClient, err := api.NewClient(config)
	if err != nil {
		panic(err)
	}
	global.ConsuleClient = consuleClient
	//注册consule   api接口端
	register_client := consule.NewRegistryClient(global.GlobalConfig.Consule.Host, global.GlobalConfig.Consule.Port)
	//在注册之前先查询  是否已经注册  如果已经注册，那就不再重新注册
	filterResult := register_client.FilterService(global.GlobalConfig.Consule.Name)
	BaseSrvIp := ""
	for _, value := range filterResult {
		BaseSrvIp = value.Address
		break
	}
	if BaseSrvIp == "" {
		serviceId := fmt.Sprintf("%s", uuid.NewV4())
		err = register_client.Register(global.GlobalConfig.Host, global.Port, global.GlobalConfig.Consule.Name, global.GlobalConfig.Consule.Tag, serviceId)
		if err != nil {
			panic(err)
			zap.S().Panic("服务注册失败:", err.Error())
		}
	} else {
		zap.S().Info("服务已经注册，无需再次注册")
	}
}
